var fs = require("fs");
var path = require("path");
var uglifyjs = require("uglify-js");
var uglifycss = require("uglifycss");

module.exports = function compress(fileList, outputPath) {
  let inputText = "";
  let outputText = "";
  try {
    // 读取输入文件
    for (let i = 0; i < fileList.length; i++) {
      let filePath = path.normalize(fileList[i]);
      let fileText = fs.readFileSync(filePath, "utf8");
      inputText += fileText;
      console.log(">", filePath);
    }
    // 以后缀名判断压缩方式
    let suffix = path.extname(outputPath).toLowerCase();
    if (suffix === ".js") {
      outputText = uglifyjs.minify(inputText, { mangle: true })["code"];
    } else if (suffix === ".css") {
      outputText = uglifycss.processString(inputText, { expandVars: false });
    }
    outputText = outputText.replaceAll("\n", "\\n");
    // 输出到指定路径
    let filePath = path.normalize(__dirname + "/../" + outputPath);
    fs.writeFileSync(filePath, outputText, "utf8");
    // 结束输出
    console.log("Successfully compressed the files to " + filePath + "\n");
  } catch (error) {
    // 异常提前退出
    console.error(error.message);
    return;
  }
};
